import axios from 'axios'
import {ElMessage} from 'element-plus'


const request = axios.create()


// 添加请求拦截器
request.interceptors.request.use(
    (config) => config,
    (error) => Promise.reject(error)
)


const errorHandle = (status: any, other: any) => {
    switch (status) {
        case 400:
            ElMessage.error('信息校验失败')
            break
        case 401:
            ElMessage.error('认证失败')
            break
        case 403:
            ElMessage.error('token校验失败')
            break
        case 404:
            ElMessage.error('请求的资源不存在')
            break
        default:
            ElMessage.error(other)
            break
    }
}

// 添加响应拦截器
request.interceptors.response.use(
    (res) => (res.status === 200 ? Promise.resolve(res) : Promise.reject(res)),
    (err) => {
        ElMessage.error(err)
        const {response} = err
        if (response) {
            errorHandle(response.status, response.data);
            return Promise.reject(response)
        }
        ElMessage.error('请求失败')
        return true
    }
)


export default request
